
uniform sampler2D		alphaMap;
uniform sampler2D		bumpMap;
uniform samplerCube	reflectionMap;
uniform sampler2D		refractionMap;

uniform vec2		xyScale;			// Passed in automatically
uniform vec2		potAdjust;			// Passed in automatically
uniform float		lightScale;			// Passed in automatically
uniform vec3		specularColor;
uniform float		specularExponent;
uniform float		specularBrightness;

varying vec3		viewVector;
varying vec3		lightVector;
varying vec2		alphaTexCoord;
varying vec4		bumpTexCoord;
varying mat3		tangentToGlobal;
varying float		deformScale;


void main (void){

	vec3		viewVec, lightVec, halfAngleVec, normalVec, reflectionVec;
	vec3		reflection, refraction, specular, color;
	vec2		texCoord;
	float		mask;

	// Normalize the view vector
	viewVec = normalize(viewVector);

	// Normalize the light vector
	lightVec = normalize(lightVector);

	// Load the mask from the alpha map
	mask = texture2D(alphaMap, alphaTexCoord).a;

	// Load the normal vector from the bump map
	normalVec = (texture2D(bumpMap, bumpTexCoord.st).rgb * 2.0 - 1.0) + (texture2D(bumpMap, bumpTexCoord.pq).rgb * 2.0 - 1.0);
	normalVec = normalize(normalVec);

	// Load the reflection map
	reflectionVec = reflect(-viewVec, normalVec) * tangentToGlobal;

	reflection = textureCube(reflectionMap, reflectionVec).rgb;

	// Load the refraction map with a modified texcoord
	texCoord = (gl_FragCoord.xy * xyScale) + (normalVec.xy * deformScale * mask);
	texCoord = clamp(texCoord, 0.0, 1.0) * potAdjust;

	refraction = texture2D(refractionMap, texCoord).rgb;

	// Blend reflection and refraction, using the fresnel term as the blend factor
	color = mix(reflection, refraction, dot(viewVec, normalVec));

	// Compute specular light contribution
	halfAngleVec = normalize(viewVec + lightVec);

	specular = specularColor * lightScale;
	specular *= pow(max(dot(halfAngleVec, normalVec), 0.0), specularExponent) * specularBrightness;

	// Add color and specular to become the final color, and copy the mask to alpha
	gl_FragColor = vec4(color + specular, mask);
}
